<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function f(val) {
            var a = document.getElementById("yhm");
            if (a.value.length<=8){
                document.getElementById('zf').innerText = 8-parseInt(a.value.length);
            } else {
                b = a.value.substring(0,8);
                document.getElementById("yhm").value = b;
            }
        }
    </script>
</head>
<body>
    <h1>限制输入字符数</h1>
    用户名:<br>
    <input type="text" id="yhm" onkeyup="f(this.id)">用户最多输入8个字符<br>
    还能输入:<font id="zf">8</font>个字符
</body>
</html>